<?php

namespace App\Filament\Resources;

use App\Enums\BorrowStatus;
use App\Filament\Resources\BorrowRecordResource\Pages;
use App\Filament\Resources\BorrowRecordResource\RelationManagers;
use App\Models\BorrowRecord;
use App\Settings\Borrow;
use Carbon\Carbon;
use Filament\Tables\Actions\Action;
use Filament\Forms;
use Filament\Forms\Form;
use Filament\Resources\Resource;
use Filament\Tables;
use Filament\Tables\Columns\Layout\Panel;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\SoftDeletingScope;

class BorrowRecordResource extends Resource
{
    protected static ?string $model = BorrowRecord::class;

    protected static ?string $navigationIcon = 'heroicon-o-rectangle-stack';
    protected static ?string $navigationGroup = '会员中心';

    protected static ?string $navigationLabel = '借阅管理';

    protected static ?string $modelLabel = '借阅记录';

    public static function form(Form $form): Form
    {
        return $form
            ->schema([
                //
                Forms\Components\Select::make('book_id')
                    ->label('借阅图书')
                    ->relationship('book', 'title')
                    ->searchable()
                    ->native(false)
                    ->required(),
                Forms\Components\Select::make('member_id')
                    ->label('借阅人')
                    ->relationship('member', 'name')
                    ->searchable(['name', 'email','phone','real_name'])
                    ->native(false)
                    ->required(),
                Forms\Components\Textarea::make('remark')
                    ->label('备注')
                    ->rows(3)
                    ->nullable(),
            ]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->defaultSort('created_at', 'desc')
            ->columns([
                //
                Tables\Columns\TextColumn::make('book.title')
                    ->label('书名')
                    ->searchable(),
                Tables\Columns\TextColumn::make('member.name')
                    ->label('用户')
                    ->description(fn (BorrowRecord $record): string => $record->remark)
                    ->searchable(),
                Tables\Columns\TextColumn::make('returned')
                    ->label('状态')
                    ->formatStateUsing(fn (BorrowRecord $record) =>
                       $record->returned->getLabelText()
                   )
                    ->badge()
                    ->color(fn (BorrowStatus $state): string => $state->getColor())
                    ->description(function (BorrowRecord $record,Borrow $settings) {
                        return $record->returned == BorrowStatus::STATUS_OVERDUE ? '逾期罚金：'. Carbon::now()->diffInDays($record->borrow_date?->addDays($settings->borrow_days)) * $settings->borrow_overdue_price: '';
                    })
                    ->searchable(),
                Tables\Columns\TextColumn::make('borrow_date')
                    ->label('借阅时间')
                    ->searchable(),
            ])
            ->filters([
                Tables\Filters\Filter::make('created_at')
                ->form([
                    Forms\Components\Grid::make()
                    ->schema([
                        Forms\Components\DatePicker::make('start_at')
                            ->columnSpan(1)
                            ->label('开始日期'),
                        Forms\Components\DatePicker::make('end_at')
                            ->columnSpan(1)
                            ->label('结束日期'),
                    ])

                ])->query(function (Builder $query, $data) {

                     return   $query->when(
                            $data['start_at'],
                            fn (Builder $query, $date): Builder => $query->whereDate('created_at', '>=', $data['start_at']),
                        )->when(
                         $data['end_at'],
                         fn (Builder $query, $date): Builder => $query->whereDate('created_at', '<=', $data['end_at']),
                     );

                }),
            ],Tables\Enums\FiltersLayout::AboveContent)
            ->filtersFormColumns(4)
            ->actions([
                Action::make('归还')
                    ->visible(fn (BorrowRecord $record) => $record->returned == BorrowStatus::STATUS_BORROWING)
                    ->label('归还')
                    ->icon('heroicon-o-document-check')
                    ->requiresConfirmation()
                    ->modalHeading('归还图书')
                    ->modalDescription('确认用户已归还此图书吗?')
                    ->modalSubmitActionLabel('确认')
                    ->modalCancelActionLabel('取消')
                    ->action(function (BorrowRecord $record){
                        $record->update([
                            'returned' => BorrowStatus::STATUS_RETURNED,
                            'due_date' => now(),
                        ]);
                        $record->book()->increment('quantity');
                }),
                Action::make('审核')
                    ->visible(fn (BorrowRecord $record) => $record->returned == BorrowStatus::STATUS_APPLY)
                    ->label('审核')
                    ->icon('heroicon-o-cog-6-tooth')
                    ->requiresConfirmation()
                    ->modalHeading('借阅审核')
                    ->modalDescription('确认通过借阅吗?')
                    ->modalSubmitActionLabel('确认')
                    ->modalCancelActionLabel('取消')
                    ->action(function (BorrowRecord $record,Borrow $settings){
                        $record->update([
                            'returned' => BorrowStatus::STATUS_BORROWING,
                            'borrow_date' => now(),
                            'deadline' => Carbon::now()->addDays($settings->borrow_days),
                        ]);
                        $record->book()->decrement('quantity');
                    }),
                Action::make('续期')
                    ->visible(fn (BorrowRecord $record) => $record->returned == BorrowStatus::STATUS_OVERDUE)
                    ->label('续期')
                    ->icon('heroicon-o-forward')
                    ->requiresConfirmation()
                    ->modalHeading('借阅续期')
                    ->modalDescription('请确认已处理逾期罚金，确认续期吗?')
                    ->modalSubmitActionLabel('确认')
                    ->modalCancelActionLabel('取消')
                    ->action(function (BorrowRecord $record,Borrow $settings){
                        $record->update([
                            'returned' => BorrowStatus::STATUS_BORROWING,
                            'deadline' => Carbon::now()->addDays($settings->borrow_days),
                        ]);
                    }),
                Tables\Actions\EditAction::make(),
            ])
            ->bulkActions([
                Tables\Actions\BulkActionGroup::make([
                    Tables\Actions\DeleteBulkAction::make(),
                ]),
            ]);
    }

    public static function getRelations(): array
    {
        return [
            //
        ];
    }

    public static function getPages(): array
    {
        return [
            'index' => Pages\ListBorrowRecords::route('/'),
            'create' => Pages\CreateBorrowRecord::route('/create'),
            'edit' => Pages\EditBorrowRecord::route('/{record}/edit'),
        ];
    }
}
